'use client'

import { Fragment } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { 
  XMarkIcon, 
  PlayIcon, 
  MusicalNoteIcon, 
  PhotoIcon,
  ArrowDownTrayIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
  EyeIcon,
  HeartIcon,
  ChatBubbleLeftIcon,
  ShareIcon,
  UserIcon,
  CalendarIcon,
  HashtagIcon
} from '@heroicons/react/24/outline'

interface Video {
  id: number
  videoId: string
  url: string
  title: string | null
  description: string | null
  author: string | null
  authorId: string | null
  authorFollowers: number | null
  authorFollowing: number | null
  likes: number | null
  shares: number | null
  comments: number | null
  views: number | null
  duration: number | null
  videoUrl: string | null
  audioUrl: string | null
  coverUrl: string | null
  hashtags: string | null
  musicTitle: string | null
  musicAuthor: string | null
  publishTime: string | null
  localVideoPath: string | null
  localAudioPath: string | null
  localCoverPath: string | null
  downloadStatus: string | null
  downloadProgress: number | null
  fileSize: number | null
  createdAt: string
  textExtractions: {
    id: number
    status: string
    method: string
    extractedText: string
  }[]
  rewrittenTexts?: {
    id: number
    originalText: string
    rewrittenText: string
    style: string
    tone: string
    length: string
    requirements?: string
    createdAt: string
  }[]
}

interface VideoDetailModalProps {
  video: Video | null
  isOpen: boolean
  onClose: () => void
  onDownload?: (videoId: number) => void
}

// 辅助函数：将本地文件路径转换为API路径
function getLocalFileApiPath(localPath: string): string {
  if (!localPath) return ''

  // 提取downloads目录后的相对路径
  const downloadsIndex = localPath.indexOf('downloads/')
  if (downloadsIndex === -1) return ''

  const relativePath = localPath.substring(downloadsIndex + 'downloads/'.length)
  return `/api/files/${relativePath}`
}

export default function VideoDetailModal({ video, isOpen, onClose, onDownload }: VideoDetailModalProps) {
  if (!video) return null

  const formatNumber = (num: number | null) => {
    if (!num) return '0'
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  const formatDuration = (seconds: number | null) => {
    if (!seconds) return '未知'
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  const formatFileSize = (bytes: number | null) => {
    if (!bytes) return '未知'
    if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`
    if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${bytes} B`
  }

  const getDownloadStatusBadge = () => {
    switch (video.downloadStatus) {
      case 'completed':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
            <CheckCircleIcon className="h-3 w-3 mr-1" />
            已下载
          </span>
        )
      case 'downloading':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
            <ClockIcon className="h-3 w-3 mr-1" />
            下载中 {video.downloadProgress}%
          </span>
        )
      case 'failed':
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
            <XCircleIcon className="h-3 w-3 mr-1" />
            下载失败
          </span>
        )
      default:
        return (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
            <ClockIcon className="h-3 w-3 mr-1" />
            待下载
          </span>
        )
    }
  }

  const hashtags = video.hashtags ? JSON.parse(video.hashtags) : []

  return (
    <Transition appear show={isOpen} as={Fragment}>
      <Dialog as="div" className="relative z-50" onClose={onClose}>
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black bg-opacity-25" />
        </Transition.Child>

        <div className="fixed inset-0 overflow-y-auto">
          <div className="flex min-h-full items-center justify-center p-4 text-center">
            <Transition.Child
              as={Fragment}
              enter="ease-out duration-300"
              enterFrom="opacity-0 scale-95"
              enterTo="opacity-100 scale-100"
              leave="ease-in duration-200"
              leaveFrom="opacity-100 scale-100"
              leaveTo="opacity-0 scale-95"
            >
              <Dialog.Panel className="w-full max-w-4xl transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                <div className="flex justify-between items-start mb-6">
                  <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
                    视频详情
                  </Dialog.Title>
                  <button
                    type="button"
                    className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    onClick={onClose}
                  >
                    <XMarkIcon className="h-6 w-6" />
                  </button>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  {/* 左侧：视频预览和基本信息 */}
                  <div className="space-y-4">
                    {/* 视频封面 */}
                    {video.coverUrl && (
                      <div className="aspect-video bg-gray-100 rounded-lg overflow-hidden">
                        <img
                          src={video.localCoverPath ? `/api/files/covers/${video.videoId}_cover.jpg` : video.coverUrl}
                          alt="视频封面"
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement;
                            target.src = video.coverUrl || '';
                          }}
                        />
                      </div>
                    )}

                    {/* 基本信息 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h4 className="font-medium text-gray-900 mb-2">基本信息</h4>
                      <div className="space-y-2 text-sm">
                        <div><span className="font-medium">视频ID:</span> {video.videoId}</div>
                        <div><span className="font-medium">标题:</span> {video.title || '无标题'}</div>
                        <div><span className="font-medium">时长:</span> {formatDuration(video.duration)}</div>
                        <div><span className="font-medium">发布时间:</span> {video.publishTime ? new Date(video.publishTime).toLocaleString() : '未知'}</div>
                        <div><span className="font-medium">采集时间:</span> {new Date(video.createdAt).toLocaleString()}</div>
                      </div>
                    </div>

                    {/* 描述 */}
                    {video.description && (
                      <div className="bg-gray-50 rounded-lg p-4">
                        <h4 className="font-medium text-gray-900 mb-2">视频描述</h4>
                        <p className="text-sm text-gray-700 whitespace-pre-wrap">{video.description}</p>
                      </div>
                    )}

                    {/* 话题标签 */}
                    {hashtags.length > 0 && (
                      <div className="bg-gray-50 rounded-lg p-4">
                        <h4 className="font-medium text-gray-900 mb-2 flex items-center">
                          <HashtagIcon className="h-4 w-4 mr-1" />
                          话题标签
                        </h4>
                        <div className="flex flex-wrap gap-2">
                          {hashtags.map((tag: any, index: number) => (
                            <span
                              key={index}
                              className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                            >
                              #{tag.name || tag}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* 右侧：详细数据 */}
                  <div className="space-y-4">
                    {/* 作者信息 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h4 className="font-medium text-gray-900 mb-2 flex items-center">
                        <UserIcon className="h-4 w-4 mr-1" />
                        作者信息
                      </h4>
                      <div className="space-y-2 text-sm">
                        <div><span className="font-medium">昵称:</span> {video.author || '未知'}</div>
                        <div><span className="font-medium">用户ID:</span> {video.authorId || '未知'}</div>
                        {video.authorFollowers && (
                          <div><span className="font-medium">粉丝数:</span> {formatNumber(video.authorFollowers)}</div>
                        )}
                        {video.authorFollowing && (
                          <div><span className="font-medium">关注数:</span> {formatNumber(video.authorFollowing)}</div>
                        )}
                      </div>
                    </div>

                    {/* 互动数据 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h4 className="font-medium text-gray-900 mb-2">互动数据</h4>
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div className="flex items-center">
                          <EyeIcon className="h-4 w-4 mr-2 text-gray-500" />
                          <span>观看: {formatNumber(video.views)}</span>
                        </div>
                        <div className="flex items-center">
                          <HeartIcon className="h-4 w-4 mr-2 text-red-500" />
                          <span>点赞: {formatNumber(video.likes)}</span>
                        </div>
                        <div className="flex items-center">
                          <ChatBubbleLeftIcon className="h-4 w-4 mr-2 text-blue-500" />
                          <span>评论: {formatNumber(video.comments)}</span>
                        </div>
                        <div className="flex items-center">
                          <ShareIcon className="h-4 w-4 mr-2 text-green-500" />
                          <span>分享: {formatNumber(video.shares)}</span>
                        </div>
                      </div>
                    </div>

                    {/* 音乐信息 */}
                    {(video.musicTitle || video.musicAuthor) && (
                      <div className="bg-gray-50 rounded-lg p-4">
                        <h4 className="font-medium text-gray-900 mb-2 flex items-center">
                          <MusicalNoteIcon className="h-4 w-4 mr-1" />
                          背景音乐
                        </h4>
                        <div className="space-y-1 text-sm">
                          {video.musicTitle && <div><span className="font-medium">标题:</span> {video.musicTitle}</div>}
                          {video.musicAuthor && <div><span className="font-medium">作者:</span> {video.musicAuthor}</div>}
                        </div>
                      </div>
                    )}

                    {/* 媒体文件 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h4 className="font-medium text-gray-900 mb-2">媒体文件</h4>
                      <div className="space-y-2 text-sm">
                        {video.videoUrl && (
                          <div className="flex items-center justify-between">
                            <div className="flex items-center">
                              <PlayIcon className="h-4 w-4 mr-2" />
                              <span>视频文件</span>
                              {video.localVideoPath && <CheckCircleIcon className="h-3 w-3 ml-2 text-green-500" />}
                            </div>
                            <div className="flex space-x-2">
                              {video.localVideoPath && (
                                <a
                                  href={getLocalFileApiPath(video.localVideoPath)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-green-600 hover:text-green-800 text-xs px-2 py-1 border border-green-200 rounded"
                                >
                                  本地查看
                                </a>
                              )}
                              <a href={video.videoUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-800 text-xs px-2 py-1 border border-blue-200 rounded">
                                原链接
                              </a>
                            </div>
                          </div>
                        )}
                        {video.audioUrl && (
                          <div className="flex items-center justify-between">
                            <div className="flex items-center">
                              <MusicalNoteIcon className="h-4 w-4 mr-2" />
                              <span>音频文件</span>
                              {video.localAudioPath && <CheckCircleIcon className="h-3 w-3 ml-2 text-green-500" />}
                            </div>
                            <div className="flex space-x-2">
                              {video.localAudioPath && (
                                <a
                                  href={getLocalFileApiPath(video.localAudioPath)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-green-600 hover:text-green-800 text-xs px-2 py-1 border border-green-200 rounded"
                                >
                                  本地查看
                                </a>
                              )}
                              <a href={video.audioUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-800 text-xs px-2 py-1 border border-blue-200 rounded">
                                原链接
                              </a>
                            </div>
                          </div>
                        )}
                        {video.coverUrl && (
                          <div className="flex items-center justify-between">
                            <div className="flex items-center">
                              <PhotoIcon className="h-4 w-4 mr-2" />
                              <span>封面图片</span>
                              {video.localCoverPath && <CheckCircleIcon className="h-3 w-3 ml-2 text-green-500" />}
                            </div>
                            <div className="flex space-x-2">
                              {video.localCoverPath && (
                                <a
                                  href={getLocalFileApiPath(video.localCoverPath)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-green-600 hover:text-green-800 text-xs px-2 py-1 border border-green-200 rounded"
                                >
                                  本地查看
                                </a>
                              )}
                              <a href={video.coverUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-800 text-xs px-2 py-1 border border-blue-200 rounded">
                                原链接
                              </a>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 下载状态 */}
                    <div className="bg-gray-50 rounded-lg p-4">
                      <h4 className="font-medium text-gray-900 mb-2">下载状态</h4>
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm">状态:</span>
                          {getDownloadStatusBadge()}
                        </div>
                        {video.fileSize && (
                          <div className="flex items-center justify-between text-sm">
                            <span>文件大小:</span>
                            <span>{formatFileSize(video.fileSize)}</span>
                          </div>
                        )}
                        {(!video.downloadStatus || video.downloadStatus === 'pending' || video.downloadStatus === 'failed') && onDownload && (
                          <button
                            onClick={() => onDownload(video.id)}
                            className="w-full mt-2 inline-flex items-center justify-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                          >
                            <ArrowDownTrayIcon className="h-4 w-4 mr-2" />
                            下载文件
                          </button>
                        )}
                      </div>
                    </div>

                    {/* 文案提取 */}
                    {video.textExtractions.length > 0 && (
                      <div className="bg-gray-50 rounded-lg p-4">
                        <h4 className="font-medium text-gray-900 mb-2">文案提取结果</h4>
                        <div className="space-y-3">
                          {video.textExtractions.map((extraction) => (
                            <div key={extraction.id} className="bg-white rounded-lg p-4 border">
                              <div className="flex items-center justify-between mb-3">
                                <div className="flex items-center space-x-2">
                                  <span className="font-medium text-gray-900">
                                    {extraction.method === 'aliyun_sensevoice' ? '阿里云语音识别' :
                                     extraction.method === 'OCR' ? 'OCR文字识别' :
                                     extraction.method}
                                  </span>
                                  {extraction.method === 'aliyun_sensevoice' && (
                                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800">
                                      AI语音转文字
                                    </span>
                                  )}
                                  {extraction.method === 'OCR' && (
                                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                      图像文字识别
                                    </span>
                                  )}
                                </div>
                                <span className={`px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                  extraction.status === 'completed' ? 'bg-green-100 text-green-800' :
                                  extraction.status === 'processing' ? 'bg-blue-100 text-blue-800' :
                                  extraction.status === 'failed' ? 'bg-red-100 text-red-800' :
                                  'bg-gray-100 text-gray-800'
                                }`}>
                                  {extraction.status === 'completed' ? '已完成' :
                                   extraction.status === 'processing' ? '处理中' :
                                   extraction.status === 'failed' ? '失败' : extraction.status}
                                </span>
                              </div>

                              {extraction.extractedText && (
                                <div className="space-y-2">
                                  <div className="text-sm text-gray-600">提取内容：</div>
                                  <div className="bg-gray-50 rounded p-3">
                                    <p className="text-gray-800 whitespace-pre-wrap leading-relaxed">
                                      {extraction.extractedText}
                                    </p>
                                  </div>
                                </div>
                              )}

                              {extraction.confidence && (
                                <div className="mt-2 text-xs text-gray-500">
                                  置信度: {(extraction.confidence * 100).toFixed(1)}%
                                </div>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* 改写文案 */}
                    {video.rewrittenTexts && video.rewrittenTexts.length > 0 && (
                      <div className="bg-orange-50 rounded-lg p-4 mt-4">
                        <h4 className="font-medium text-gray-900 mb-2 flex items-center">
                          <span className="mr-2">✨</span>
                          改写文案结果
                        </h4>
                        <div className="space-y-3">
                          {video.rewrittenTexts.map((rewrite) => (
                            <div key={rewrite.id} className="bg-white rounded-lg p-4 border border-orange-200">
                              <div className="flex items-center justify-between mb-3">
                                <div className="flex items-center space-x-2">
                                  <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-orange-100 text-orange-800">
                                    {rewrite.style}
                                  </span>
                                  <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                    {rewrite.tone}
                                  </span>
                                  <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                    {rewrite.length}
                                  </span>
                                </div>
                                <span className="text-xs text-gray-500">
                                  {new Date(rewrite.createdAt).toLocaleString()}
                                </span>
                              </div>

                              <div className="space-y-3">
                                <div>
                                  <div className="text-sm text-gray-600 mb-1">改写后文案：</div>
                                  <div className="bg-orange-50 rounded p-3">
                                    <p className="text-gray-800 whitespace-pre-wrap leading-relaxed">
                                      {rewrite.rewrittenText}
                                    </p>
                                  </div>
                                  <button
                                    onClick={() => navigator.clipboard.writeText(rewrite.rewrittenText)}
                                    className="mt-2 text-xs text-orange-600 hover:text-orange-800"
                                  >
                                    复制改写文案
                                  </button>
                                </div>

                                {rewrite.requirements && (
                                  <div>
                                    <div className="text-sm text-gray-600 mb-1">改写要求：</div>
                                    <div className="bg-gray-50 rounded p-2">
                                      <p className="text-sm text-gray-700">
                                        {rewrite.requirements}
                                      </p>
                                    </div>
                                  </div>
                                )}

                                <div className="border-t pt-2">
                                  <div className="text-sm text-gray-600 mb-1">原始文案：</div>
                                  <div className="bg-gray-50 rounded p-2">
                                    <p className="text-sm text-gray-700 line-clamp-3">
                                      {rewrite.originalText}
                                    </p>
                                  </div>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                <div className="mt-6 flex justify-end space-x-3">
                  <a
                    href={video.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    <EyeIcon className="h-4 w-4 mr-2" />
                    查看原视频
                  </a>
                  <button
                    type="button"
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    onClick={onClose}
                  >
                    关闭
                  </button>
                </div>
              </Dialog.Panel>
            </Transition.Child>
          </div>
        </div>
      </Dialog>
    </Transition>
  )
}
